package pearson.automation.forms.upload;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import framework.BaseForm;
import framework.elements.Button;
import framework.elements.ElementList;
import framework.elements.TextBox;

public class UploadDetailsForm extends BaseForm {
    
    private static Button save = new Button(By.xpath("//input[@value='Save']"),  "Save");
    //private Link cancel = new Link(By.linkText("Cancel"), "Cancel");
    
    private static ElementList uploadedList = new ElementList(By.xpath("//fieldset/div[contains(@class, 'upload-item')]/div/h5"),  "Uploaded items");
    
    private String uploadID;

    private TextBox title;
    private TextBox description;
    private TextBox tags;
    
    public UploadDetailsForm() {
    super(save.getLocator(), "Upload details form");
    // Initialize elements using upload ID from cancel URL 
    uploadID = save.getElement().getAttribute("name").split("_")[0];
    title = new TextBox(By.id(uploadID + "_title"), "Title");
    description = new TextBox(By.id(uploadID + "_description"), "Description");
    tags = new TextBox(By.className("textboxlist-bit-editable-input"), "Tags");
    
    title.assertIsPresent();
    description.assertIsPresent();
    tags.assertIsPresent();
    }

    public void setTitle(String title) {
    this.title.setText(title);
    }

    public void setDescription(String description) {
    this.description.setText(description);
    }

    public void setTags(String tags) {
    this.tags.setText(tags);
    }

    public UploadBranchForm clickSave() {
    save.clickAndWait();
    browser.waitForPageToLoad();
    return new UploadBranchForm();
    }
    
    public Object[] getRecentlyAddedSection() {
        ArrayList<String> recentlyAdded = new ArrayList<String>();
        List<WebElement> list = uploadedList.getListElements();
        Collections.reverse(list);
        for (WebElement element: list) {
            recentlyAdded.add(element.getText());
        }
        return recentlyAdded.toArray();
    }
}
